<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>表格+画布+拖拽</title>
    <style type="text/css">
        * {
            padding: 0;
            margin: 0;
        }

        html,
        body {
            width: 100%;
            height: 100%;
        }
        .container {
            display: flex;
            flex-direction: column;
        }

        #box {
            margin: auto;
            width: 810px;
            height: 600px;
            border: 6px solid #000000;
            display: flex;
            flex-wrap: wrap;
            align-items: flex-start;
            box-sizing: content-box;
        }
        #box div{
            box-sizing: border-box;
        }

        .item {
            width: 150px;
            height: 100px;
            border-radius: 5px;
            margin: 0 5px 5px 0;
            float: left;
            border: 1px solid lightgray;
            z-index: 1;
            cursor: move;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-around;
        }

        div.moving {
            border: 1px dashed gray;
            background: white;
        }

        div.draging {
            width: 150px;
            height: 100px;
            position: absolute;
            background: goldenrod;
            box-shadow: 0 0 2px 2px #555;
            border-radius: 5px;
            z-index: 500;
        }

        .conten {
            width: 100%;
            height: 50px;
            position: relative;
        }

        .conten_img {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 1;
        }

        .name {
            font-size: 28px;
            font-weight: bold;
            color: red;
            z-index: 12;
        }

        #list {
            width: 350px;
            height: 600px;
            border: 1px solid #000;
            position: relative;
        }

        .comp {
            width: 150px;
            height: 100px;
            border-radius: 5px;
            margin: 5px;
            float: left;
            background: goldenrod;
            border: 1px solid lightgray;
            z-index: 1;
            cursor: move;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-around;
        }

        .comp_img {
            width: 60px;
            height: 50px;
            background-color: #1a252f;
        }

        .status {
            font-size: 14px;
        }

        .list_name {
            font-size: 18px;
            font-weight: bold;
        }

        #operation {
            width:12vw;
            border: 1px solid #000;
            padding: 10px 30px;
            display: flex;
            flex-direction: column;
        }
        #operation button{
            margin: 4px;
            cursor: pointer;
        }
        table{
            border: 1px solid #000;
        }
        table tr td{
            border: 1px solid #000;
        }
        .parant{
            border: 0px solid #000;
        }
        .from-box  input{
           width: 28%;
        }
    </style>
</head>

<body>
<div class="container">
    <div style="display: flex">
        <div id="operation">
            <div class="from-box">
                <div class="title">设置box宽高</div>
                <input type="number" id="i_width" value="800">*
                <input type="number" id="i_height" value="400">
                <div class="title">根据行列设置大小</div>
                <input type="number" id="i_row" value="8">*
                <input type="number" id="i_culomn" value="4">

                <button class="sub" id="setBOX">设置</button>
            </div>
            <div class="title">操作按钮</div>
            <button  onclick="createTable(5,4);">根据AJAX数据创建表格</button>
            <button  onclick="createTable(5,4);">创建5行4列表格</button>
            <button  onclick="createTable(2,3);">创建2*3</button>
            <button  onclick="createTable(2,1);">创建2*1</button>
            <button  onclick="createTable(1,4);">创建1*4</button>
            <button  onclick="createTable(4,1);">创建4*1</button>
            <button onclick="getTableData()">获取表格数据</button>

        </div>
        <div id="box"></div>
        <div id="list">
            <div class="item">
                <video autoplay src="img/video1.mp4" class="comp_img"></video>
                <div class="status">未开机</div>
                <div class="list_name">调度01</div>
            </div>
            <div class="item">
                <video autoplay src="img/video2.mp4" class="comp_img"></video>
                <div class="status">已开机</div>
                <div class="list_name">调度02</div>
            </div>
            <div class="item">
                <video autoplay src="img/video3.mp4" class="comp_img"></video>
                <div class="status">已开机</div>
                <div class="list_name">调度03</div>
            </div>
            <div class="item"></div>
            <div class="item"></div>
        </div>
    </div>


</div>
<script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/data.js"></script>
<script>
    console.log(dataFromJSON)
    console.log(dataFromJSON.table.child)
    let child = dataFromJSON.table.child;
    let list = dataFromJSON.list;

    let nowData = []
    child.forEach(v => {
        list.forEach(y => {
            console.log( y.id)
           if(v == y.id){
               nowData.push(nowData)
           }
        })
    })
    console.log('当前符合的数据',nowData)
    var item_w,item_h;
    $("#setBOX").click(function(){
        console.log('设置宽高', $("#i_width").val(),$("#i_height").val())
        let i_width =  $("#i_width").val();
        let i_height =  $("#i_height").val();
        $('#box').width( i_width).height(i_height);
        item_w = i_width/$("#i_row").val() - 5
        item_h = i_height/$("#i_culomn").val() - 5
        console.log('重新设置宽高',item_w,item_h)

        console.log($('#box .item'))
    });
    function getTableData() {
        var formData = {};
        var t = $('#box').serializeArray();
        console.log(t)
        $.each(t, function () {
            formData[this.name] = this.value;
        });
        console.log(JSON.stringify(formData));
        alert("Hello World!");
    }
    /** 练习1：创建单行单列的表格 */
    function createTable(row,column){
        console.log(`创建 ${row}行 ${column}列 DIV`)
        var $parant = $(`<div class="parant" style="width: ${column*item_w+column*5}px;"></div>`)
        for(let r=0;r<row;r++){
            for(let c=0;c<column;c++){
                let $item  = $(`<div class="item">第${r+1}行${c+1}列</div>`)
                $parant.append($item)
            }
        }
        console.log($parant)
        $("#box").append($parant)
        console.log('最终设置item 宽度',item_w,item_h)
        $('.item').width( item_w-2).height(item_h-2);
        addFun()
    }
    function addFun(){
        var Astop = true, Bstop = true;
        var Parent = '', toParent = '';
        var a_b = false, b_a = false, a_a = false, b_b = false;//定义两个 模块的 插入关系
        $('.container .item').on('mousedown', function (e) {
                if (Astop) {
                    if(e.offsetX <= 4 || e.offsetY <= 4) return //防止误操作 故改为距离边框 4 才可进行拖拽操作
                    console.log('选择模块', e)
                    console.log('选择模块2', $(this).position())
                    Parent = this.parentNode.id //当前要替换的dom 的 父ID
                    Astop = false;
                    let that = this;
                    let disx = e.offsetX; //获取的拖拽过程的短线的长度（鼠标的位置离盒子边缘的位置）
                    let disy = e.offsetY;
                    let disx2 = e.clientX; //获取的拖拽过程的短线的长度（鼠标的位置离盒子边缘的位置）
                    let disy2 = e.clientY;
                    let $clone = $(this).clone(); //克隆
                    $clone.addClass('draging').css(Parent == 'list' ? {top: $(that).position().top, left: disx2 - e.offsetX} : { //对克隆的盒子设置类名以及位置
                        left: $(this).position().left,
                        top: $(this).position().top
                    });
                    $('.container').append($clone); //追加到box里面
                    $(this).addClass('moving').html(''); //被克隆的元素添加类移除内容
                    $('.container').on('mousemove', function (e) { //对克隆的盒子进行拖拽
                        $clone.css({
                            left: e.pageX - $(this).offset().left - disx,
                            top: e.pageY - $(this).offset().top - disy
                        })

                    });

                    $clone.on('mouseup', function () {
                            $('.container').off('mousemove'); //取消mousemove事件
                            let minIndex = $(that).index(); //最小索引赋初始值
                            console.log('最小索引赋初始值',$(that.parentNode).index)
                            console.log('最小索引赋初始值',minIndex)
                            let minValue = 1000; //初始化最小值，用来存储所有盒子的最小值
                            $('.container .item').not(':last').each(function () { //不包括克隆的那个盒子
                                let smalldistance = Math.sqrt(Math.pow($clone.position().left - $(this).position().left, 2) + Math.pow($clone.position().top - $(this).position().top, 2)); //利用勾股定理获取每一个盒子离克隆出来的盒子的距离
                                if (smalldistance < minValue) { //比较
                                    minValue = smalldistance; //获取最小值
                                    minIndex = $(this).index(); //获取最小值对应的索引
                                }
                            });
                            console.log('筛选div的长度', $('.container .item').not(':last'))
                            console.log('获取最小值对应的索引minIndex', minIndex)
                            if (minIndex == $(that).index()) { //如果当前最小距离的那个盒子和拖拽的盒子索引相等的话，归位。
                                $clone.animate($(that).position(), 400, function () {
                                    $(that).removeClass('moving').html($clone.html()); //恢复被克隆盒子的相关样式
                                    $(this).remove(); //移除被克隆的盒子
                                    Astop = true;
                                });
                            } else {
                                let $minbox = $('.container .item ').eq(minIndex); //最小索引的盒子
                                console.log($minbox[0].parentNode.id)
                                toParent = $minbox[0].parentNode.id
                                let $clone2 = $minbox.clone(); //克隆一个最小盒子的副本，添加相关样式
                                console.log('clone2的移动效果', $minbox.position().left, $minbox.position().top)
                                $clone2.addClass('draging').css({
                                    left: $minbox.position().left,
                                    top: $minbox.position().top
                                })
                                $('.container').append($clone2); //追加
                                $minbox.addClass('moving').html('');
                                $clone.animate($minbox.position(), 400, function () { //克隆的内容运动到最小索引的盒子的位置
                                    $minbox.removeClass('moving').html($clone.html()); //移除相关样式，添加内容
                                    $clone.remove(); //移除克隆的盒子
                                    Astop = true;
                                });
                                console.log('克隆的内容运动到指定位置', $(that).position(), {disy2, disx2})
                                // $clone2.animate({
                                //     top:disy2,
                                //     left:disx2
                                // }, 400, function () {
                                // $clone2.animate(
                                //     Parent == toParent ?$(that).position() : {top:disy,left:disx2} , 400, function () {
                                // $clone2.animate(
                                //     $(that).position(), 400, function() {
                                $clone2.animate(
                                    Parent == toParent ? $(that).position() : {
                                        top: $(that).position().top,
                                        left: disx2
                                    }, 400, function () {
                                        $(that).removeClass('moving').html($clone2.html());
                                        $clone2.remove();
                                        Astop = true;
                                    });
                            }
                        }
                    )
                    ;
                }
                return false;
            }
        )
        ;
    }
</script>
</body>

</html>
